package com.itheima.core.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.common.web.Constants;
import com.itheima.core.dao.product.ProductDao;
import com.itheima.core.dao.product.SkuDao;
import com.itheima.core.pojo.product.Brand;
import com.itheima.core.pojo.product.Product;
import com.itheima.core.pojo.product.ProductQuery;
import com.itheima.core.pojo.product.Sku;
import com.itheima.core.pojo.product.SkuQuery;

import cn.itcast.common.page.Pagination;
import redis.clients.jedis.Jedis;

/**
 * @author zhang.cheng
 *
 *         2017年3月9日
 */
@Service("searchService")
@Transactional
public class SearchServiceImpl implements SearchService {

	private static Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class);
	@Autowired
	private SolrServer solrServer;

	@Autowired
	private ProductDao productDao;

	@Autowired
	private SkuDao skuDao;

	@Override
	public Pagination selectPaginationFromSolrByQuery(Integer pageNo, String keyword, String price, Long brandId)
			throws Exception {
		// 创建商品的条件对象
		ProductQuery productQuery = new ProductQuery();
		// 当前页
		if (pageNo != null) {
			productQuery.setPageNo(Pagination.cpn(pageNo));
		}
		// 每页数
		productQuery.setPageSize(10);

		// 查询
		SolrQuery solrQuery = new SolrQuery();
		StringBuilder sb = new StringBuilder();
		// 关键词查询
		if (keyword != null) {
			solrQuery.setQuery(keyword);
			sb.append("keyword=").append(keyword);
		}
		// 默认域
		solrQuery.set("df", "name_ik");
		// 过滤条件
		// 品牌id
		if (null != brandId) {
			solrQuery.addFilterQuery("brandId=" + brandId);
			sb.append("&brandId=").append(brandId);
		}
		// 价格
		if (null != price) {
			String[] p = price.split("-");
			if (p.length == 2) {
				solrQuery.addFilterQuery("price:[" + p[0] + " TO " + p[1] + "]");
			} else {
				solrQuery.addFilterQuery("price:[" + p[0] + " TO *]");
			}
			sb.append("&price=").append(price);
		}

		// 高亮
		// 1.打开高亮的开关
		solrQuery.setHighlight(true);
		// 2.设置高亮的域
		solrQuery.addHighlightField("name_ik");
		// 3.前缀
		solrQuery.setHighlightSimplePre("<span style='color:red'>");
		// 4.后缀
		solrQuery.setHighlightSimplePost("</span>");

		// 分页
		solrQuery.setStart(productQuery.getStartRow());
		// 每页数
		solrQuery.setRows(productQuery.getPageSize());
		// 排序
		solrQuery.addSort("price", ORDER.asc);

		// 执行查询
		QueryResponse response = solrServer.query(solrQuery);
		// 获取高亮的数据
		Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();

		// 取出结果集
		SolrDocumentList results = response.getResults();
		// 取出总条数
		long numFound = results.getNumFound();

		// 创建商品结果集
		List<Product> productList = new ArrayList<Product>();

		// 遍历结果集
		for (SolrDocument result : results) {
			Product product = new Product();
			// 商品id
			String id = (String) result.get(("id"));
			product.setId(Long.parseLong(id));
			// 商品名称
			Map<String, List<String>> map = highlighting.get(id);
			List<String> list = map.get("name_ik");
			// product.setName((String) result.get("name_ik"));
			product.setName(list.get(0));

			// 商品价格
			product.setPrice((Float) result.get("price"));
			// 商品图片
			// System.out.println((String) result.get("url"));
			String urls = (String) result.get("url");
			if (urls != null) {
				String[] splitUrls = urls.split(",");
				System.out.println(Constants.BASE_Img_URL + splitUrls[0]);
				product.setImgUrl(Constants.BASE_Img_URL + splitUrls[0]);
			}

			productList.add(product);
		}

		// 创建分页对象
		Pagination pagination = new Pagination(productQuery.getPageNo(), productQuery.getPageSize(), (int) numFound);
		pagination.setList(productList);

		// 页面展示路径
		String url = "/search";
		pagination.pageView(url, sb.toString());
		return pagination;
	}

	// 从redis中查询品牌结果集
	@Autowired
	private Jedis jedis;

	@Override
	public List<Brand> selectBrandListFromRedis() {
		List<Brand> brandList = new ArrayList<Brand>();
		Map<String, String> hgetAll = jedis.hgetAll("brand");
		Set<Entry<String, String>> entrySet = hgetAll.entrySet();
		for (Entry<String, String> entry : entrySet) {
			Brand brand = new Brand();
			brand.setId(Long.parseLong(entry.getKey()));
			brand.setName(entry.getValue());
			brandList.add(brand);
		}
		return brandList;
	}

	public void insertProductToSolr(Long id) {
		try {

		// 保存商品的信息到solr服务器
		SolrInputDocument doc = new SolrInputDocument();

		// 商品id
		doc.setField("id", id);

		// 商品名称
		Product product2 = productDao.selectByPrimaryKey(id);
		doc.setField("name_ik", product2.getName());
		// 品牌id
		doc.setField("brandId", product2.getBrandId());

		// 图片url
		doc.setField("url", product2.getImgUrl());

		// 价格
		SkuQuery skuQuery = new SkuQuery();
		skuQuery.createCriteria().andProductIdEqualTo(id);
		skuQuery.setOrderByClause("price asc");
		skuQuery.setPageNo(1);
		skuQuery.setPageSize(1);

		skuQuery.setFields("price");
		List<Sku> skus = skuDao.selectByExample(skuQuery);
		doc.setField("price", skus.get(0).getPrice());

			solrServer.add(doc);
			System.out.println("activemq接收商品id为：" + id + "的商品上架到solr索引库成功");
			logger.info("activemq接收商品id为：" + id + "的商品上架到solr索引库成功");
			solrServer.commit();
		} catch (Exception e) {
		}
	}
}
